//
//  WBNetworkManager+Extension.swift
//  传智微博
//
//  Created by zhoujiming on 2017/1/19.
//  Copyright © 2017年 gmcc. All rights reserved.
//

import Foundation

extension WBNetworkManager{
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0, completion:@escaping (_ list:[[String : AnyObject]]?, _ isSuccess : Bool)->()){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //let params = ["access_token" : "2.00fEiw_CA3HTUD71ce9b46e11lQlIE"]
        let max = (max_id==0) ? 0 : max_id-1
        
        let params = ["since_id":"\(since_id)", "max_id":"\(max)"]
        
        
        tokenRequest(method: WBHTTPMethod.GET, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            print(json as AnyObject)
            
            let result = json? ["statuses"] as? [[String : AnyObject]]
            
            completion(result, isSuccess)
            
        }

    }
    
    func unreadCount(completion:@escaping (_ count:Int)->()){
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let param = ["uid" : uid]
        
        tokenRequest(URLString: urlString, parameters: param as [String : AnyObject]?) {(json, isSuccess) in
        
            let dict = json as? [String:AnyObject]
            
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
        
    }
}

// MARK: - OAuth相关方法
extension WBNetworkManager {
    
    /// 提问：网络请求异步到底应该返回什么？-需要什么返回什么？
    /// 加载 AccessToken
    ///
    /// - parameter code:       授权码
    /// - parameter completion: 完成回调[是否成功]
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey,
                      "client_secret": WBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WBRedirectURI]
        
        // 发起网络请求
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            //print(json)
            
            // 如果请求失败，对用户账户数据不会有任何影响
            // 直接用字典设置 userAccount 的属性
            self.userAccount.yy_modelSet(with: (json as? [String: AnyObject]) ?? [:])
            
            //print(self.userAccount)
            
            // 加载用户数据
            self.loadUserInfo(completion: { (dict) in
                print(dict)
                // 使用用户信息字典设置用户信息（昵称，头像）
                self.userAccount.yy_modelSet(with: dict)
                
                // 保存模型
                self.userAccount.saveAccount()
                
                // 用户信息加载完成再，完成回调
                completion(isSuccess)
            })
            
        }
    }
}

// 用户信息
extension WBNetworkManager{
    func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject])->()){
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid": uid]
        
        // 发起网络请求
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?){(json, isSuccess) in
            // 完成回调
            completion(json as! [String : AnyObject] ?? [:])
        }
    }
}
